using System.Reflection;
using UnityEditor;
using UnityEngine;

namespace Framework
{
    [CustomPropertyDrawer(typeof(ButtonFuncAttribute))]
    public class ButtonFuncDrawer : PropertyDrawer
    {
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            // var target = property.serializedObject.targetObject;
            var target = GetTarget(property);
            var attr = attribute as ButtonFuncAttribute;
            var method = target.GetType().GetMethod(attr.MethodName);
            if (method == null) return;
            string name = string.IsNullOrWhiteSpace(attr.ButtonName) ? method.Name : attr.ButtonName;
            if (GUI.Button(position, name)) method.Invoke(target, null);
        }

        private static object GetTarget(SerializedProperty property)
        {
            string[] path = property.propertyPath.Split('.');
            object obj = property.serializedObject.targetObject;
            for (int i = 0; i < path.Length - 1; i++)
                obj = obj.GetType().GetField(path[i]).GetValue(obj);
            return obj;
        }
    }
}